package cn.tedu.recruitmentwebsite.common.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class SmsService {

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;


    private String signName;

    @Value("${aliyun.sms.templateCode}")
    private String templateCode;

    public SendSmsResponse sendSms(String phoneNumber, String code) throws ClientException {
        log.info("开始发送验证码，手机号：{}, 验证码：{}", phoneNumber, code);
        log.info("Aliyun SMS Configurations:");
        log.info("AccessKeyId: {}", accessKeyId);
        log.info("AccessKeySecret: {}", accessKeySecret);
        log.info("SignName: {}", signName);
        log.info("TemplateCode: {}", templateCode);
        signName = "招聘网";
        // 设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

       // 初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
       IAcsClient acsClient = new DefaultAcsClient(profile);

        // 组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phoneNumber);
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        request.setTemplateParam("{\"code\":\"" + code + "\"}");

        try {
            // hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            log.info("验证码发送结果: Code={}, Message={}",
                    sendSmsResponse.getCode(),
                    sendSmsResponse.getMessage());
            return sendSmsResponse;
        } catch (ClientException e) {
            log.error("阿里云客户端异常，错误信息: {}", e.getMessage(), e);
            throw e;
        }
    }
}
